package cn.njyd.corejava.thread.myday04;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

/*
统计房产公司各个销售员的卖房业绩
 */
class House{
    int countSales = 0;
    public synchronized void getCountSales(){
        countSales++;
    }

    ThreadLocal<Integer> salePersonVolume=ThreadLocal.withInitial(()->0);
    public void countSalePersonVolume(){
        salePersonVolume.set(salePersonVolume.get()+1);
    }

}


public class ThreadLocalDemo02 {
    public static void main(String[] args) throws InterruptedException {
        House house = new House();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i=1;i<=10;i++) {
            new Thread(()->{
                try{
                    int n = ThreadLocalRandom.current().nextInt(10);
                    for (int j=1;j<=n;j++) {
                        house.getCountSales();
                        house.countSalePersonVolume();
                    }
                    System.out.println("第"+Thread.currentThread().getName()+"个销售员共卖了"+house.salePersonVolume.get()+"套");
                }finally {
                    house.salePersonVolume.remove();
                    countDownLatch.countDown();
                }

            },String.valueOf(i)).start();
        }
//        Thread.sleep(3000);
        countDownLatch.await();
        System.out.println("总业绩："+house.countSales);
    }






}
